<?php
namespace Service\Mailer;
use Swift_Mailer;
use Swift_Message;
use Swift_SmtpTransport;

/**
 * @link https://swiftmailer.symfony.com/docs/introduction.html - 文档
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2018/11/21 17:51
 * @copyright PanxSoft Inc.
 */

class SwiftMailer
{
    protected $message;

    public function __construct(\Config $config)
    {
        list($schema, $host) = $this->splitSchemaHost($this->config->get('config_mail_smtp_hostname'));

        $transport = (new Swift_SmtpTransport($host, $config->get('config_mail_smtp_port')))
            ->setUsername($config->get('config_mail_smtp_username'))
            ->setPassword($config->get('config_mail_smtp_password'));

        if ($schema) {
            $transport->setEncryption($schema);
        }

        // Create the Mailer using your created Transport
        $this->mailer = new Swift_Mailer($transport);
        $this->config = $config;
    }

    /**
     *
     * @return mixed
     */
    public function send()
    {
        return $this->mailer->send($this->message);
    }

    /**
     * @param string $title - 标题
     * @param array|string $from - 发送人 邮箱 => 名字
     * @param array|string $to - 接收人 邮箱 => 名字
     * @param $reply_to - 应回复的人
     * @param string $body - 内容
     *
     * @return $this
     */
    public function setMessage(string $title, $from, $to, $reply_to, string $body)
    {
        $this->message = (new Swift_Message($title))
            ->setFrom($from)
            ->setTo($to)
            ->addReplyTo($reply_to)
            ->setBody($body);

        return $this;
    }

    /**
     * @param $config_host
     *
     * @return array
     */
    public function splitSchemaHost(string $config_host)
    {
        $scheme_host = explode('://', $config_host);
        $cnt = count($scheme_host);
        if ($cnt === 2) {
            list($scheme, $host) = $scheme_host;
        } else if ($cnt === 1) {
            $scheme = null;
            $host = $config_host;
        } else {
            throw new \InvalidArgumentException("Invalidate format, hostname: [$config_host]");
        }

        return [$scheme, $host];
    }
}